#!/bin/bash

function short_version() {
	local __long_version=$1
	local __version_split=(${__long_version//./ })
	local __major=${__version_split[0]}
	local __minor=${__version_split[1]}
	echo "${__major}.${__minor:0:1}"
}

if [[ -z "$CONFIG_FILE" ]]; then
	FILENAME="/opt/selenium/config.toml"
else
	FILENAME="$CONFIG_FILE"
fi

echo "[events]
publish = \"tcp://${SE_EVENT_BUS_HOST}:${SE_EVENT_BUS_PUBLISH_PORT}\"
subscribe = \"tcp://${SE_EVENT_BUS_HOST}:${SE_EVENT_BUS_SUBSCRIBE_PORT}\"
" >"$FILENAME"

if [[ -z "${SE_NODE_HOST}" ]] && [[ -z "${SE_NODE_PORT}" ]]; then
	echo "Configuring server..."
else
	echo "[server]" >>"$FILENAME"
fi

if [[ -z "${SE_NODE_HOST}" ]]; then
	echo "Setting up SE_NODE_HOST..."
else
	echo "host = \"${SE_NODE_HOST}\"" >>"$FILENAME"
fi

if [[ -z "${SE_NODE_PORT}" ]]; then
	echo "Setting up SE_NODE_PORT..."
else
	echo "port = \"${SE_NODE_PORT}\"" >>"$FILENAME"
fi

echo "[node]" >>"$FILENAME"
# String, Url where the Grid can be reached
if [[ -z "${SE_NODE_GRID_URL}" ]]; then
	echo "Setting up SE_NODE_GRID_URL..."
else
	echo "grid-url = \"${SE_NODE_GRID_URL}\"" >>"$FILENAME"
fi
echo "session-timeout = \"${SE_NODE_SESSION_TIMEOUT}\"" >>"$FILENAME"
echo "override-max-sessions = ${SE_NODE_OVERRIDE_MAX_SESSIONS}" >>"$FILENAME"
echo "detect-drivers = false" >>"$FILENAME"
echo "drain-after-session-count = ${DRAIN_AFTER_SESSION_COUNT:-$SE_DRAIN_AFTER_SESSION_COUNT}" >>"$FILENAME"
# When node is handled both browser and relay, SE_NODE_MAX_CONCURRENCY is used to configure max concurrency based on sum of them
echo "max-sessions = ${SE_NODE_MAX_CONCURRENCY:-${SE_NODE_MAX_SESSIONS}}
" >>"$FILENAME"

if [ -f /opt/selenium/browser_name ]; then
	SE_NODE_BROWSER_NAME=$(cat /opt/selenium/browser_name)
fi
if [ -f /opt/selenium/browser_version ]; then
	SE_NODE_BROWSER_VERSION=$(short_version $(cat /opt/selenium/browser_version))
fi
if [ -f /opt/selenium/browser_binary_location ]; then
	SE__BROWSER_BINARY_LOCATION=$(cat /opt/selenium/browser_binary_location)
fi

# 'browserName' is mandatory for default stereotype
if [[ -z "${SE_NODE_STEREOTYPE}" ]] && [[ -n "${SE_NODE_BROWSER_NAME}" ]]; then
	SE_NODE_STEREOTYPE="{\"browserName\": \"${SE_NODE_BROWSER_NAME}\", \"browserVersion\": \"${SE_NODE_BROWSER_VERSION}\", \"platformName\": \"Linux\", ${SE__BROWSER_BINARY_LOCATION}, \"se:containerName\": \"${SE_NODE_CONTAINER_NAME}\"}"
else
	SE_NODE_STEREOTYPE="${SE_NODE_STEREOTYPE}"
fi

# 'stereotype' setting is mandatory
if [[ -n "${SE_NODE_STEREOTYPE}" ]]; then
	echo "[[node.driver-configuration]]" >>"$FILENAME"
	echo "display-name = \"${SE_NODE_BROWSER_NAME}\"" >>"$FILENAME"
	echo "stereotype = '${SE_NODE_STEREOTYPE}'" >>"$FILENAME"
	echo "max-sessions = ${SE_NODE_MAX_SESSIONS}
    " >>"$FILENAME"
fi
